package slidingwindow;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {
    public static void main(String[] args) {
     int[] nums ={1,-1,-1,0};
        System.out.println(threeSum(nums));
    }
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; ) {
            if(nums[i] > 0) break;
            int left = i+1, right = nums.length-1, target = -nums[i];
            while(left < right) {
                int sum = nums[left] + nums[right];
                if (sum > target) {
                    right--;
                } else if (sum < target) {
                    left++;
                } else {
                    ret.add(new ArrayList<>(Arrays.asList(nums[left], nums[right], nums[i])));
                    left++;
                    right--;
                    //去重
                    while (left < right && nums[left] == nums[left - 1]) left++;
                    while (left < right && nums[right] == nums[right + 1]) right--;
                }
            }
            i++;
            while(i < nums.length && nums[i] == nums[i-1]) i++;
        }
        return ret;
    }
}
